﻿using UnityEngine;
using Network;
using LitJson;

public class ProcLogin : Proc {

    public ProcLogin()
        : base(ProcType.PROC_LOGIN)
    {

    }

    public override void process()
    {
        NetManager.Instance.Tick(Time.deltaTime);
    }

    public override void onBegin(object[] param)
    {
        RegistUIEvent();
        RegistNetworkEvent();
        UnityEngine.SceneManagement.SceneManager.LoadScene("login");
        NetManager.Instance.Destroy();
        NetManager.Instance.Connect(Config.JavaServerIp, Config.JavaTcpPort);
        IsInit = true;
    }

    public override void onEnd()
    {
        UnregistUIEvent();
        UnregistNetworkEvent();
    }

    void RegistUIEvent()
    {
    }

    void RegistNetworkEvent()
    {
        NetManager.Instance.tcpConc.connectionDelegate += onConnectSuccess;
        NetManager.Instance.RegistMsg((ushort)JsonMsgId.LogonResponse, onLogin);
    }

    void UnregistUIEvent()
    {
    }

    void UnregistNetworkEvent()
    {
        NetManager.Instance.tcpConc.connectionDelegate -= onConnectSuccess;
        NetManager.Instance.UnregistMsg((ushort)JsonMsgId.LogonResponse, onLogin);
    }

    void onConnectSuccess()
    {
        Spinning.Instance.SetActive(false);
        JsonData loginData = new JsonData();
        loginData["guid"] = Shipwar.SDK.SDK.GetInstance().currentUser.AppUID;
        loginData["token"] = Shipwar.SDK.SDK.GetInstance().currentUser.APPToken;
        loginData["channel"] = "JJ";
        loginData["version"] = Mainloop.Instance.AppVersion;
        loginData["firstLogon"] = true;
        NetManager.Instance.sendTcpMsg((ushort)JsonMsgId.LogonRequest, loginData.ToJson());
    }

    private void onLogin(object f_msg)
    {
        JsonData result = (JsonData)f_msg;
        int code = (int)result["code"];
        if (code == 0)
        {
            result = result["value"];
            long uid = (long)result["uid"];
            DetailPlayer.Instance.PlayerID = uid;
            JsonData kcpState = result["kcpState"];
            if (kcpState == null)
            {
                Mainloop.Instance.ctrl.changeProc(ProcType.PROC_LOBBY);
            }
            else
            {
                string host = (string)kcpState["host"];
                ushort port = (ushort)((int)kcpState["port"]);
                uint conv = (uint)((int)kcpState["conv"]);
                Mainloop.Instance.ctrl.changeProc(ProcType.PROC_GAME, host, port, conv);
            }
        }
        else
        {
            string reason = (string)result["msg"];
            Debug.LogError("Login Error, Reason: " + reason);
        }
    }

    

    public override void onTcpDisconnected()
    {

    }
}
